/*
 * RequestContext.java
 * Copyright 2021 Qunhe Tech, all rights reserved.
 * Qunhe PROPRIETARY/CONFIDENTIAL, any form of usage is subject to approval.
 */

package top.bbman.boot.auth.context;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.boot.actuate.endpoint.SecurityContext;

import static top.bbman.boot.auth.context.PeaThreadContext.*;


public class PeaRequestContext {

    public static final String ZEUS_REQUEST = SecurityContext.class.getName() + "_ZEUS_REQUEST_KEY";

    /**
     * 设置线程的变量
     *
     * @param request
     */
    public static void bindRequest(ZeusRequest request) {
        if (request != null) {
            put(ZEUS_REQUEST, request);
        }
    }

    /**
     * 取消线程中的变量
     *
     * @return
     */
    public static ZeusRequest unbindRequest() {
        return (ZeusRequest) remove(ZEUS_REQUEST);
    }

    /**
     * 获取当前请求，包括从Web端来的请求和dubbo来的请求
     *
     * @return
     */
    public static ZeusRequest getRequest() {
        return (ZeusRequest) get(ZEUS_REQUEST);
    }

    /**
     * 获取客户端的请求IP地址，非nginx的IP
     *
     * @return
     */
    public static String getRequestIp() {
        return getRequest() != null ? getRequest().getIp() : "";
    }

    /**
     * 输出当前请求的信息
     */
    public static String dumpRequest() {
        return dumpRequest(getRequest());
    }

    public static String getUserId() {
        ZeusRequest request = getRequest();
        if (null == request) {
            return "visitor";
        }
        return request.getUserId() == null ? "visitor" : request.getUserId();
    }


    public static String getToken() {
        ZeusRequest request = getRequest();
        if (null == request) {
            return "visitor";
        }
        return request.getToken() == null ? "visitor" : request.getToken();
    }

    public static String dumpRequest(ZeusRequest request) {

        if (request == null) {
            return "null request";
        }

        ToStringBuilder builder = new ToStringBuilder(request, ToStringStyle.SHORT_PREFIX_STYLE);
        return builder.toString();
    }

}
